import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { InfoCircleOutlined, UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  message,
  Col,
  Modal,
  Select,
  Button,
  Radio,
  Upload,
  DatePicker,
  Input,
  Checkbox,
  Tooltip,
} from 'antd';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; // 引入头部组件
import StandardTable from '@/components/StandardTable';
import { requestHeadersMd5 } from '@/utils/utils';
import getSys from './judgeSys';

const { MonthPicker } = DatePicker;
const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;
const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 9,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 9,
    },
  },
};

@connect(({ annualbasic, loading, login }) => ({
  annualbasic,
  login,
  loading: loading.effects['annualbasic/areaList'],
  loadingSave:
    loading.effects['annualbasic/saveDataNs'] || loading.effects['annualbasic/saveDataOs'],
  tableLoading: loading.effects['annualbasic/getAdjAccoInfor'],
}))
class AnnualBasicAdd extends PureComponent {
  state = {
    visAdjAcco: false,
    selectedKeys: [],
    selectedRows: [],
    insuranceArr: []
  };

  componentDidMount() {
    const { dispatch, location, login } = this.props;
    const { systemList, baseUser } = login;
    const userType = getSys(systemList, baseUser, location);
    const { yearAdjTskId } = location.query;
    this.setState({
      yearAdjTskId,
    });
    dispatch({
      type: 'annualbasic/areaList',
      payload: {},
    });

    if (yearAdjTskId) {
      // 修改页的详情
      dispatch({
        type: 'annualbasic/getBaseInfo',
        payload: { yearAdjTskId: location.query.yearAdjTskId, userType },
      });
    }
    this.setState({ userType });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    const oper = {
      yearAdjTskId: null,
      areaId: null,
      adjYm: null,
      adjTskBeginDate: null,
      adjTskEndDate: null,
      validYm: null,
      billUpdtWay: '1',
      diffHandle: [],
      listAdjAcco: [],

      fileListOld: [],
      affix: '',
      remark: null,
      includeDeduSign: 2,
      pageDataDetail: {
        list: [],
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
        },
      },
    };
    dispatch({
      type: 'annualbasic/updateModelData',
      payload: oper,
    });
  }

  updateOnChange = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'annualbasic/updateModelData',
      payload: { billUpdtWay: e.target.value },
    });
  };

  // 获取账户列表
  getAdjAcco = (currentPage = 1, pageSize = 10) => {
    const { form, dispatch } = this.props;
    const getFieldsList = form.getFieldsValue();
    const pageArg = { currentPage, pageSize };
    if (getFieldsList.areaId) {
      this.setState({
        visAdjAcco: true,
        // selectedKeys: [],
        // selectedRows: [],
      });
      dispatch({
        type: 'annualbasic/getAdjAccoInfor',
        payload: {
          areaId: getFieldsList.areaId,
          payWay: getFieldsList.payWay ? getFieldsList.payWay : '0',
          accoName: getFieldsList.accoName,
          accoTypeId: getFieldsList.accoTypeId ? getFieldsList.accoTypeId : '0',
          pageArg,
        },
      });
    } else {
      message.warning('请先选择地区，再选择账户');
    }
  };

  getBigAss = selectedRows => {
    const obj = {};
    obj.listAdjAcco = selectedRows.map(item => ({
      accoId: item.accoId,
      adjAss: item.kindId,
      accoType: item.accoTypeId,
      payWay: item.payWay,
      accoState: item.accoState,
      containAss: item.kindId,
      kindName: item.kindName,
    }));
    const bigAss = obj.listAdjAcco;
    this.assChange(bigAss);
    this.setState({
      visAdjAcco: false,
      listAdjAcco: bigAss,
    });
  };

  assChange = bigAss => {
    const { dispatch, form } = this.props;
    const getFieldsList = form.getFieldsValue();
    const a = [];
    bigAss.forEach(item => {
      if (item.adjAss) {
        const c = item.adjAss.split(',');
        const d = item.kindName.split(',');
        c.forEach((value, key) => {
          const b = {};
          b.ass = value;
          b.assName = d[key];
          a.push(b);
        });
      }
    });
    dispatch({
      type: 'annualbasic/getSelectBigAss',
      payload: { accoAssList: a, areaId: getFieldsList.areaId },
    });
  };

  okAdjAcco = () => {
    const { form } = this.props;
    const { selectedRows } = this.state;
    form.resetFields(['payWay', 'accoName']);
    this.getBigAss(selectedRows);
    form.setFieldsValue({
      'assCollectScope': []
    })
  };

  cancelAdjAcco = () => {
    const { dispatch, form } = this.props;
    const getFieldsList = form.getFieldsValue();
    dispatch({
      type: 'annualbasic/getBigAss',
      payload: { areaId: getFieldsList.areaId },
    });
    this.setState({
      visAdjAcco: false,
      selectedKeys: [],
      selectedRows: [],
      listAdjAcco: [],
    });
  };

  onAreaChange = value => {
    const { dispatch, form } = this.props;
    this.setState({ listAdjAcco: [], selectedRows: [] });
    dispatch({
      type: 'annualbasic/getBigAss',
      payload: { areaId: value },
    });
    form.setFieldsValue({
      assCollectScope: []
    })
  };

  // 选择采集险种范围
  selectProducts = insuranceArr => {
   this.setState({
    insuranceArr: insuranceArr
   })
  };

  // 保存
  insert = () => {
    const {
      form,
      dispatch,
      annualbasic: { fileListOld, includeDeduSign },
    } = this.props;

    const { listAdjAcco, userType } = this.state;

    form.validateFieldsAndScroll((err, values) => {
      const fieldsValue = values;
      Object.keys(fieldsValue).forEach(key => {
        if (
          key === 'adjYm' ||
          key === 'adjTskBeginDate' ||
          key === 'adjTskEndDate' ||
          key === 'validYm'
        ) {
          fieldsValue[key] = moment(fieldsValue[key]).valueOf();
        }
        delete fieldsValue.accuName;
        delete fieldsValue.payWay;
      });
      fieldsValue.listAdjAcco = listAdjAcco;
      fieldsValue.includeDeduSign = includeDeduSign;
      fieldsValue.billUpdtWay = fieldsValue.billUpdtWay ? fieldsValue.billUpdtWay : '1';
      if (fileListOld && fileListOld.length) {
        if (fileListOld[0].response && fileListOld[0].response.success) {
          fieldsValue.affix = fileListOld[0].response.data;
        } else {
          fieldsValue.affix = fileListOld[0].uid.concat('|').concat(fileListOld[0].name);
        }
      } else {
        fieldsValue.affix = '';
      }
      if (!err) {
        if (Number(userType) === 4) {
          // 运行
          dispatch({
            type: 'annualbasic/saveDataOs',
            payload: fieldsValue,
          });
        } else {
          // 自主供应商
          dispatch({
            type: 'annualbasic/saveDataNs',
            payload: fieldsValue,
          });
        }
      }
    });
  };

  close = () => {
    router.goBack();
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    this.getAdjAcco(pagination.current, pagination.pageSize);
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedKeys) => {
    this.setState({ selectedRows, selectedKeys });
  };

  // 单选款的选择方法
  boxChange = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'annualbasic/updateModelData',
      payload: {
        includeDeduSign: value.target.checked ? 1 : 2,
      },
    });
  };

  disabledMkupEndDate = current => {
    const { form } = this.props;
    const getFieldsList = form.getFieldsValue();
    const nowSelectDate = getFieldsList.adjTskBeginDate;
    return (
      current &&
      current <
        moment(nowSelectDate)
          .subtract(1, 'days')
          .endOf('day')
    );
  };

  disabledMkupCollect = current =>
    current &&
    current >
      moment()
        .subtract(0, 'days')
        .endOf('day');

  // 当前日以后
  disabledMkupStartDate = current => {
    const { form } = this.props;
    const getFieldsList = form.getFieldsValue();
    const nowSelectDate = getFieldsList.adjTskEndDate;
    if (nowSelectDate) {
      return (
        current <
          moment(
            moment()
              .subtract(1, 'days')
              .format('YYYY-MM-DD')
          ).endOf('day') || current > moment(nowSelectDate).endOf('day')
      );
    }
    return (
      current <
      moment(
        moment()
          .subtract(1, 'days')
          .format('YYYY-MM-DD')
      ).endOf('day')
    );
  };

  render() {
    const { visAdjAcco, selectedRows, selectedKeys, yearAdjTskId ,insuranceArr } = this.state;
    const { form, annualbasic, dispatch, loadingSave, tableLoading } = this.props;
    const { areaList, fileListOld, pageDataDetail, includeDeduSign } = annualbasic;
    const { getFieldDecorator } = form;
    const getFieldsList = form.getFieldsValue();
    const nowYear = () => {
      const date = new Date();
      return date.getFullYear();
    };
    const props = {
      name: 'file',
      action: '/esApi/fileServer/uploadFile',
      headers: {
        authorization: 'authorization-text',
        ...requestHeadersMd5(),
      },
      onChange: ({ file }) => {
        if (file.status === 'done' && file.response.success) {
          message.success(file.response.message);
        } else if (file.status === 'error') {
          message.error(`文件上传失败！`);
        }
      },
      onRemove: ({ fileList }) => {
        dispatch({
          type: 'annualbasic/updateData',
          payload: fileList,
        });
      },
      fileList: fileListOld,
      beforeUpload: (file, fileList) => {
        if (!fileListOld || fileListOld.length < 1) {
          dispatch({
            type: 'annualbasic/updateData',
            payload: fileList,
          });
        } else {
          message.error('建议一次只能上传一个文件！');
          dispatch({
            type: 'annualbasic/updateDel',
            payload: fileList,
          });
          return false;
        }
        return true;
      },
    };
    const formItemLayout2 = {
      labelCol: {
        span: 7,
      },
      wrapperCol: {
        span: 17,
      },
    };
    const columns = [
      {
        title: '缴纳方式',
        dataIndex: 'payWayName',
      },
      {
        title: '账户名称',
        dataIndex: 'accoName',
      },
      {
        title: '险种',
        dataIndex: 'kindName',
      },
    ];

    const assCollectScope = !!yearAdjTskId && annualbasic.assCollectScope &&  annualbasic.assCollectScope.length ? annualbasic.assCollectScope.map(Number) : []
    
    return (
      <div>
        <PageHeaderWrapper />
        <Card style={{ marginTop: 14, padding: '0 28px' }}>
          <FormItem {...formItemLayout} label={<span>调整年度</span>}>
            <span style={{ height: 32, lineHeight: '32px', display: 'inline-block' }}>
              {nowYear()}
            </span>
          </FormItem>
          <div style={{ marginTop: -20 }}>
            <FormItem {...formItemLayout} label={<span>地区</span>}>
              {getFieldDecorator('areaId', {
                rules: [
                  {
                    required: true,
                    message: '请选择地区',
                  },
                ],
                initialValue: annualbasic.areaId || undefined,
              })(
                <Select
                  style={{ width: '100%' }}
                  placeholder="请选择"
                  onChange={this.onAreaChange}
                  disabled={!!yearAdjTskId}
                >
                  {areaList.map(value => (
                    <Option key={value.areaId}>{value.areaName}</Option>
                  ))}
                </Select>
              )}
              <Col span={24}>
                <span>
                  <Button
                    type="primary"
                    onClick={() => this.getAdjAcco()}
                    style={{ marginRight: 6, marginTop: 10 }}
                    disabled={!!yearAdjTskId}
                  >
                    选择账户
                  </Button>
                  <span>
                    已选
                    {selectedRows.length ||
                      (annualbasic.listAdjAcco && annualbasic.listAdjAcco.length) ||
                      0}
                    个账户
                  </span>
                  <span style={{ color: '#f00', display: 'block', marginTop: 10 }}>
                    注：不选择账户，以选择的地区里全部账户数据采集。
                  </span>
                </span>
              </Col>
            </FormItem>
          </div>
          <FormItem {...formItemLayout} label="采集险种范围">
                {getFieldDecorator('assCollectScope', {
                  rules: [{ required: true, message: '请选择采集险种范围' }],
                  initialValue: assCollectScope ,
                })(
                <Select placeholder="请选择" mode="multiple"  onChange={this.selectProducts} style={{ width: '100%' }}  disabled={!!yearAdjTskId}>
                  {annualbasic.diffHandle.map(one => (
                    <Option key={one.ass} value={one.ass} datas={one}>
                      {one.assName}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          <div>
            <FormItem
              {...formItemLayout}
              label={
                <span>
                  采集年月人员
                  <Tooltip title="已回盘的账单年月人员数据">
                    <InfoCircleOutlined />
                  </Tooltip>
                </span>
              }
            >
              {getFieldDecorator('adjYm', {
                rules: [
                  {
                    required: true,
                    message: '请选择采集人员年月',
                  },
                ],
                initialValue: annualbasic.adjYm ? moment(annualbasic.adjYm, 'YYYY-MM') : undefined,
              })(
                <MonthPicker
                  size="default"
                  placeholder="请选择采集人员年月"
                  style={{ width: '100%' }}
                  disabled={!!yearAdjTskId}
                  disabledDate={current => this.disabledMkupCollect(current)}
                />
              )}
              <Checkbox
                checked={+includeDeduSign === 1}
                onChange={this.boxChange}
                disabled={!!yearAdjTskId}
                style={{ marginTop: 10 }}
              >
                包含减员数据{' '}
              </Checkbox>
              <Tooltip title="如果勾选:以采集年月的全部人员数据为准;如果不选择:采集年月人员当前发起调基时在缴纳账户下为在职的人员为准">
                <InfoCircleOutlined />
              </Tooltip>
            </FormItem>
          </div>
          <FormItem {...formItemLayout} label={<span>采集任务开始日期</span>}>
            {getFieldDecorator('adjTskBeginDate', {
              rules: [
                {
                  required: true,
                  message: '请选择采集任务开始日期',
                },
              ],
              initialValue: annualbasic.adjTskBeginDate
                ? moment(annualbasic.adjTskBeginDate, 'YYYY-MM-DD')
                : undefined,
            })(
              <DatePicker
                size="default"
                placeholder="请选择采集任务开始日期"
                style={{ width: '100%' }}
                disabledDate={current => this.disabledMkupStartDate(current)}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={<span>采集任务结束日期</span>}>
            {getFieldDecorator('adjTskEndDate', {
              rules: [
                {
                  required: true,
                  message: '请选择采集任务结束日期',
                },
              ],
              initialValue: annualbasic.adjTskEndDate
                ? moment(annualbasic.adjTskEndDate, 'YYYY-MM-DD')
                : undefined,
            })(
              <DatePicker
                size="default"
                placeholder="请选择采集任务结束日期"
                style={{ width: '100%' }}
                disabledDate={current => this.disabledMkupEndDate(current)}
              />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label={
              <span>
                开始生效年月
                <Tooltip title="调整的新基数生效日期">
                  <InfoCircleOutlined />
                </Tooltip>
              </span>
            }
          >
            {getFieldDecorator('validYm', {
              rules: [
                {
                  required: true,
                  message: '请选择开始生效年月',
                },
              ],
              initialValue: annualbasic.validYm
                ? moment(annualbasic.validYm, 'YYYY-MM')
                : undefined,
            })(
              <MonthPicker
                size="default"
                placeholder="请选择开始生效年月"
                format="YYYY-MM-01"
                style={{ width: '100%' }}
              />
            )}
          </FormItem>
          {(getFieldsList.areaId || annualbasic.areaId) && (
            <div>
              <FormItem
                {...formItemLayout}
                label={
                  <span>
                    账单更新方式
                    <Tooltip title="每个险种的差异金额在账单上的补退处理方式">
                      <InfoCircleOutlined />
                    </Tooltip>
                  </span>
                }
              >
                {getFieldDecorator('billUpdtWay', {
                  rules: [
                    {
                      required: true,
                      message: '请选择账单更新方式',
                    },
                  ],

                  initialValue: `${annualbasic.billUpdtWay}`,
                })(
                  <Radio.Group onChange={this.updateOnChange}>
                    <Radio value="1">相同</Radio>
                    <Radio value="2">不相同</Radio>
                  </Radio.Group>
                )}
              </FormItem>
              {String(annualbasic.billUpdtWay) === '1' ? (
                <div>
                  {yearAdjTskId && (
                    <FormItem {...formItemLayout} style={{ display: 'none' }}>
                      {getFieldDecorator(`listAdjUpdt[0][tskUpdtId]`, {
                        initialValue: annualbasic.tskUpdtId,
                      })(<span />)}
                    </FormItem>
                  )}
                  <FormItem {...formItemLayout} label={<span>历史账单更新方式</span>}>
                    {getFieldDecorator(`listAdjUpdt[0][differHdlWay]`, {
                      rules: [
                        {
                          required: true,
                          message: '请选择历史账单更新方式',
                        },
                      ],
                      initialValue: `${annualbasic.sameHandle.length &&
                        annualbasic.sameHandle[0].differHdlWay}`,
                    })(
                      <Radio.Group>
                        <Radio value="1">只补不退</Radio>
                        <Radio value="2">多退少补</Radio>
                      </Radio.Group>
                    )}
                  </FormItem>
                </div>
              ) : (
                annualbasic.diffHandle.map((item, i) => {
                  if(insuranceArr.some(value => value === item.ass) || !!yearAdjTskId){
                    return(
                    <div key={item.ass}>
                    {yearAdjTskId && (
                      <FormItem {...formItemLayout} style={{ display: 'none' }}>
                        {getFieldDecorator(`listAdjUpdt[${i}][tskUpdtId]`, {
                          initialValue: item.tskUpdtId,
                        })(<span />)}
                      </FormItem>
                    )}

                    <FormItem {...formItemLayout} style={{ display: 'none' }}>
                      {getFieldDecorator(`listAdjUpdt[${i}][ass]`, {
                        initialValue: item.ass,
                      })(<span />)}
                    </FormItem>
                    <div>
                      <FormItem
                        {...formItemLayout}
                        label={<span>{`${item.assName}历史账单更新方式`}</span>}
                      >
                        {getFieldDecorator(`listAdjUpdt[${i}][differHdlWay]`, {
                          rules: [
                            {
                              required: true,
                              message: '请选择历史账单更新方式',
                            },
                          ],
                          initialValue: `${item.differHdlWay}`,
                        })(
                          <Radio.Group>
                            <Radio value="1">只补不退</Radio>
                            <Radio value="2">多退少补</Radio>
                          </Radio.Group>
                        )}
                      </FormItem>
                    </div>
                  </div>
                  )}
                })
              )}
            </div>
          )}
          <div style={{ marginTop: 4 }}>
            <FormItem {...formItemLayout} label={<span>政策解读</span>} style={{ marginTop: 4 }}>
              {getFieldDecorator('remark', {
                rules: [
                  {
                    required: true,
                    message: '请填写政策解读',
                  },
                ],
                initialValue: annualbasic.remark,
              })(<TextArea placeholder="请填写政策解读" />)}
            </FormItem>
          </div>
          <div style={{ marginTop: 2 }}>
            <FormItem {...formItemLayout} label={<span>上传附件</span>} style={{ marginTop: 4 }}>
              {getFieldDecorator('affix', {
                rules: [
                  {
                    required: false,
                    message: '请上传附件',
                  },
                ],
                initialValue: fileListOld,
              })(
                <Upload {...props}>
                  <Button>
                    <UploadOutlined /> 上传
                  </Button>
                </Upload>
              )}
            </FormItem>
          </div>
        </Card>
        <FooterToolbar>
          <Button style={{ marginLeft: 15 }} onClick={this.close}>
            取消
          </Button>
          <Button type="primary" loading={loadingSave} onClick={() => this.insert()}>
            发布
          </Button>
        </FooterToolbar>
        <Modal
          title="请选择账户"
          visible={visAdjAcco}
          onOk={this.okAdjAcco}
          onCancel={this.cancelAdjAcco}
          width="40%"
        >
          <Form>
            <div gutter={8}>
              <Col span={12}>
                <FormItem {...formItemLayout2} label="缴纳方式：">
                  {getFieldDecorator('payWay', {
                    rules: [
                      {
                        required: false,
                        message: '请选择缴纳方式：',
                      },
                    ],
                  })(
                    <Select showSearch style={{ width: '100%' }} placeholder="请选择缴纳方式">
                      <Option key="0"> 全部</Option>
                      <Option key="2"> 大库</Option>
                      <Option key="1"> 单立户</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem {...formItemLayout2} label="账户名称:">
                  {getFieldDecorator('accoName', {
                    rules: [
                      {
                        required: false,
                        message: '请选择材料类型',
                      },
                    ],
                  })(<Input />)}
                </FormItem>
              </Col>
            </div>
            <div>
              <Col span={12}>
                <FormItem {...formItemLayout2} label="缴纳产品:">
                  {getFieldDecorator('accoTypeId', {
                    rules: [
                      {
                        required: false,
                        message: '请选择缴纳产品',
                      },
                    ],
                  })(
                    <Select showSearch style={{ width: '100%' }} placeholder="请选择缴纳产品">
                      <Option key="0"> 全部</Option>
                      <Option key="1"> 社保</Option>
                      <Option key="2"> 公积金</Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={4} style={{ marginTop: 3 }} offset={1}>
                <Button type="primary" onClick={() => this.getAdjAcco()}>
                  查询
                </Button>
              </Col>
            </div>
          </Form>
          <StandardTable
            selectedRows={selectedRows}
            selectedRowKeys={selectedKeys}
            data={pageDataDetail}
            rowKey="accoId"
            columns={columns}
            loading={tableLoading}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Modal>
      </div>
    );
  }
}
const AnnualBasicAddform = Form.create()(AnnualBasicAdd);
export default AnnualBasicAddform;
